<?php
function get_admin_token($t = '')
{
  if (empty($_SESSION['token_admin'])) return false;

  list($id, $name, $rand_int) = explode('+', hex_bin($_SESSION['token_admin']));

  switch ($t) {
    case 'id':
      $res = intval($id);
      break;

    case 'token':
      $res = $rand_int;
      break;

    case 'array':
      $res['id'] = $id;
      $res['name'] = $name;
      $res['token'] = $rand_int;
      break;

    default:
      $res = str_safe($name);
      break;
  }

  return $res;
}

function get_admin_token_cookie()
{
  if (empty($_COOKIE['token_admin'])) return false;

  list($id, $name, $rand_int) = explode('+', hex_bin($_COOKIE['token_admin']));

  $res['id'] = $id;
  $res['name'] = $name;
  $res['token'] = $rand_int;

  return $res;
}

/**
 * 检测用户登录状态
 */
function check_admin($url = '', $conf = true)
{
  // 判空
  if (empty($_COOKIE['token_admin']) || empty($_SESSION['token_admin'])) {
    href($url);
    // alert_href($GLOBALS['lang']['uc']['check']['failed'], $url);
  }

  // 限制同一用户同时多端登录
  if ($conf) {
    if ($_COOKIE['token_admin'] == $_SESSION['token_admin']) {
      return true;
    }

    alert_href($GLOBALS['lang']['uc']['check']['failed'], $url);
  }

  $admin_token = get_admin_token('array');
  $admin_token_cookie = get_admin_token_cookie();

  if ($admin_token['id'] != $admin_token_cookie['id'] || $admin_token['name'] != $admin_token_cookie['name']) {
    alert_href($GLOBALS['lang']['uc']['check']['failed'], $url);
  }

  unset($admin_token);
  unset($admin_token_cookie);

  return true;
}

/**
 * 设置用户标示便于进一步安全判断
 * 用户id
 * 用户名
 */
function set_admin_token($u_id, $u_name)
{
  $u_id = intval($u_id);
  $rand_int = str_code(6);

  $admin_token = bin2hex($u_id . '+' . $u_name . '+' . $rand_int);
  set_cookie('token_admin', $admin_token, gmtime() + COOKIE_TIMEOUT);
  $_SESSION['token_admin'] = $admin_token;
}

/**
 * 用户退出
 */
function admin_logout($url = '')
{
  $url = !empty($url) ? $url : M(str_safe($_GET['s']), 'index', 'login');
  set_cookie('token_admin', '', gmtime() - COOKIE_EXPIRE);
  unset($_SESSION['token_admin']);
  href($url);
  return;
}

function get_file_database_name($file_name)
{
  list($db_name, $date, $ext) = str_array($file_name, '.');
  return $db_name;
}

// 订单状态 0未付款 1已付款 2等待收货 3确认收货 5撤销 6退款中 7退款完成 8交易完成 9已撤销
function setOrderState($id, $n)
{
  $id = intval($id);
  return $GLOBALS['db']->query("UPDATE order SET o_state = $n WHERE id = $id");
}

// 回复评论
function answerRate($arr, $id)
{
  $id = intval($id);
  // f_id订单号;f_star评星字串;f_content留言内容;f_answer留言回复;f_date留言期;f_adate回复日期;f_ok是否回复
  return $GLOBALS['db']->autoExecute('feedback', $arr, 'UPDATE', "id = $id");
}

function moduleAdminReplace($str)
{
  global $s;

  if ('admin_b5' == $s && false === strpos($str, $s)) {
    $str = str_replace('admin', $s, $str);
  }

  if ('admin' == $s && false !== strpos($str, $s . '_')) {
    $str = str_replace('admin_b5', $s, $str);
  }

  return $str;
}


function checkAdminPriv($priv = null)
{
  if (empty($priv)) {
    return false;
  }

  $res = $GLOBALS['db']->getOne("SELECT r.r_priv FROM user AS u INNER JOIN role AS r ON r.id=u.u_rid WHERE u.id = " . get_admin_token('id'));
  // $cids = 0;

  $priv_obj = str_array($res);
  // if (preg_replace('(,)', '', preg_replace('([a-z]+,?)', '', $res))) {
  //   $cids = rtrim(preg_replace('([a-z]+,?)', '', $res), ',');
  // }

  if ($res == 'all') {
    $priv_obj = ['all'];
  }

  if ($priv_obj != ['all'] && in_array($priv, $priv_obj) === false) {
    alert_back($GLOBALS['lang']['priv']['failed']);
  }

  return true;
}

function getChannelPriv($pid, $rid, $priv)
{
  $pid = intval($pid);
  $rid = intval($rid);
  $str = '';

  $res = $GLOBALS['db']->getAll("SELECT id,c_ifsub,c_parent,c_name FROM channel WHERE c_parent=$pid ORDER BY c_order ASC, id ASC");
  foreach ($res as $val) {
    if ($val['c_parent'] == 0) {
      $str .= '<table class="table table-bordered common_table"><tr><th><label for="c' . $val['id'] . '"><input type="checkbox" name="c' . $val['id'] . '" id="c' . $val['id'] . '" value="c' . $val['id'] . '" ' . (in_array("c" . $val['id'], $priv) ? 'checked="checked"' : '') . '>' . $val['c_name'] . '</label></th>' . (empty($val['c_ifsub']) ? '<td class="gray">无子频道</td>' : '<td>' . getChannelPriv($val['id'], $rid, $priv) . '</td>')  . '</tr></table>';
    } else {
      $str .= '<label for="c' . $val['id'] . '"><input type="checkbox" name="c' . $val['id'] . '" id="c' . $val['id'] . '" value="c' . $val['id'] . '" ' . (in_array("c" . $val['id'], $priv) ? 'checked="checked"' : '') . '>' . $val['c_name'] . '</label>';
    }
    /*
    if ($val['c_ifsub'] || $val['c_parent'] == 0) {
      if ($val['c_ifsub'] == 0 && $val['c_parent'] == 0) {
        $str .= '<table class="table table-bordered common_table"><tr><th><label for="c' . $val['id'] . '"><input type="checkbox" name="c' . $val['id'] . '" id="c' . $val['id'] . '" value="c' . $val['id'] . '" ' . (in_array("c" . $val['id'], $priv) ? 'checked="checked"' : '') . '>' . $val['c_name'] . '</label></th><td class="gray">无子频道</td></tr></table>';
      } else {
        $str .= '<table class="table table-bordered common_table"><tr><th><label for="c' . $val['id'] . '"><input type="checkbox" name="c' . $val['id'] . '" id="c' . $val['id'] . '" value="c' . $val['id'] . '" ' . (in_array("c" . $val['id'], $priv) ? 'checked="checked"' : '') . '>' . $val['c_name'] . '</label></th><td>' . getChannelPriv($val['id'], $rid, $priv) . '</td></tr></table>';
      }
    } else {
      $str .= '<label for="c' . $val['id'] . '"><input type="checkbox" name="c' . $val['id'] . '" id="c' . $val['id'] . '" value="c' . $val['id'] . '" ' . (in_array("c" . $val['id'], $priv) ? 'checked="checked"' : '') . '>' . $val['c_name'] . '</label>';
    }
    */
  }
  return $str;
}

//获取频道下拉列表
function channel_select_list($pid, $sid = 0)
{
  if ('' === $pid) {
    return '';
  }

  if (0 === $pid) {
    return channel_select_list_all(0, $sid);
  }

  $tmp = '';

  $res = $GLOBALS['db']->getAll("SELECT id,c_name FROM channel WHERE id IN ($pid) ORDER BY c_order ASc, id ASC");

  if (!count($res)) {
    return $tmp;
  }

  foreach ($res as $row) {
    $select = $row['id'] == $sid ? 'selected="selected"' : '';
    $tmp .= '<option value="' . $row['id'] . '" ' . $select . '>' . $row['c_name'] . '</option>';
  }

  return $tmp;
}

function channel_select_list_all($pid = 0, $sid = 0, $level = 0)
{
  $tmp = '';
  $s = '';

  for ($i = 0; $i < $level; $i++) {
    $s = $s . '├&nbsp;';
  }

  $level = $level + 1;

  $sql = "SELECT id,c_name,c_ifsub,c_sub FROM channel WHERE c_parent IN ($pid) ORDER BY c_order ASC, id ASC";
  $res = $GLOBALS['db']->getAll($sql);
  if (!count($res)) {
    return $tmp;
  }

  foreach ($res as $row) {
    $select = $row['id'] == $sid ? 'selected="selected"' : '';
    $tmp .= '<option value="' . $row['id'] . '" ' . $select . '>' . $s . $row['c_name'] . '</option>' . channel_select_list_all($row['id'], $sid, $level);
  }

  return $tmp;
}

//获取所有频道的ID
function get_channel_sub($id)
{
  $tmp = '';
  $sql = "SELECT id,c_name,c_ifsub,c_sub FROM channel WHERE c_parent = $id ORDER BY c_order ASC , id ASC";
  $res = $GLOBALS['db']->getAll($sql);
  if (empty($res)) return '';
  foreach ($res as $key => $row) {
    $tmp .= $row['id'] . ',';
    if (!empty($row['c_ifsub'])) {
      $tmp .= get_channel_sub($row['id']);
    }
  }

  return $tmp;
}

//获取指定频道的最上级频道
function get_channel_main($id)
{
  $id = intval($id);
  $res = $GLOBALS['db']->getRow("SELECT * FROM channel WHERE id =" . $id);

  if (0 == $res['c_parent']) {
    return $id;
  }

  return get_channel_main($res['c_parent']);
}

//获取指定频道是否有子频道
function get_channel_ifsub($id)
{
  $id = intval($id);
  $res = $GLOBALS['db']->getOne("SELECT count(*) FROM channel WHERE c_parent = $id");
  return $res ? 1 : 0;
}

//更新所有频道
function update_channel()
{
  $res = $GLOBALS['db']->getAll("SELECT id,c_parent FROM channel");
  foreach ($res as $row) {
    $c_sub = rtrim(get_channel_sub($row['id']), ',');
    $c_main = get_channel_main($row['c_parent']);

    $GLOBALS['db']->query("UPDATE channel SET c_sub='$c_sub',c_ifsub='" . ($c_sub != $row['id'] && $c_sub != '' ? 1 : 0) . "',c_main='$c_main' WHERE id = " . $row['id']);
  }

  // 更新导航静态文件
  file_it(MENU_TYPE ? navigation(0, '<li><a href="/">网站首页</a></li>', 0) : nav_m(), 'html', 'navigation');
  // 更新频道管理列表文件
  file_it(channel_list(0), 'html', 'channel_list');
  return true;
}

//频道管理列表
function channel_list($priv)
{
  if ('' === $priv) {
    return '';
  }
  if (0 === $priv) {
    return channel_list_all(0, 0);
  }

  $html = '';
  $_GET['s'] = iif(str_safe($_GET['s']), DEFAULT_MODULE);


  $res = $GLOBALS['db']->getAll("SELECT id,c_order,c_name,c_cmodel,c_dmodel,c_link,c_ifcover,c_ifslideshow,c_safe FROM " . DATA_PREFIX . "channel WHERE id IN ($priv) ORDER BY c_order ASC, id ASC");
  if (!count($res)) {
    return $html;
  }

  foreach ($res as $row) {
    $cm_name = array_have(file_get('json', 'channel_model'), 'value', $row['c_cmodel'], 'name') ?: '自定义';
    $dm_name = array_have(file_get('json', 'detail_model'), 'value', $row['c_dmodel'], 'name') ?: '自定义';

    $html .= '<tr><td>' . $row['id'] . '</td><td>' . $row['c_order'] . '</td><td><a href="/' . c_url($row['id'], $row['c_link']) . '" target="_blank">' . $row['c_name'] . '</a></td><td>' . $cm_name . '</td><td>' . $dm_name . '</td><td>' . ($row['c_link'] ? '<span class="badge text-bg-primary">链接</span> ' : '') . ($row['c_ifcover'] ? '<span class="badge text-bg-primary">封面</span> ' : '') . ($row['c_ifslideshow'] ? '<span class="badge text-bg-primary">组图</span> ' : '') . ($row['c_safe'] ? '<span class="badge text-bg-primary">保护</span> ' : '') . '</td><td><a href="' . M($_GET['s'], 'channel', 'edit') . '&id=' . $row['id'] . '" >编辑</a>&nbsp;<a href="' . M($_GET['s'], 'channel', 'del') . '&id=' . $row['id'] . '" onclick="return confirm(\'确定要删除吗？\')" >删除</a></td></tr>';
  }

  return $html;
}

function channel_list_all($priv = 0, $level = 0)
{
  $priv = intval($priv);
  $t1 = intval($level);
  $tmp = '';
  $s = '';

  for ($i = 0; $i < $level; $i++) {
    $s = $s . '├&nbsp;';
  }

  $res = $GLOBALS['db']->getAll("SELECT id,c_order,c_name,c_cmodel,c_dmodel,c_link,c_ifcover,c_ifslideshow,c_safe FROM " . DATA_PREFIX . "channel WHERE c_parent = $priv ORDER BY c_order ASC, id ASC");
  if (!count($res)) return '';

  $level = $level + 1;
  $_GET['s'] = iif(str_safe($_GET['s']), DEFAULT_MODULE);

  foreach ($res as $row) {
    $cm_name = array_have(file_get('json', 'channel_model'), 'value', $row['c_cmodel'], 'name') ?: '自定义';
    $dm_name = array_have(file_get('json', 'detail_model'), 'value', $row['c_dmodel'], 'name') ?: '自定义';

    $tmp .= '<tr><td>' . $row['id'] . '</td><td>' . $row['c_order'] . '</td><td>' . $s . '<a href="/' . c_url($row['id'], $row['c_link']) . '" target="_blank">' . $row['c_name'] . '</a></td><td>' . $cm_name . '</td><td>' . $dm_name . '</td><td>' . ($row['c_link'] ? '<span class="badge text-bg-primary">链接</span> ' : '') . ($row['c_ifcover'] ? '<span class="badge text-bg-primary">封面</span> ' : '') . ($row['c_ifslideshow'] ? '<span class="badge text-bg-primary">组图</span> ' : '') . ($row['c_safe'] ? '<span class="badge text-bg-primary">保护</span> ' : '') . '</td><td><a href="' . M($_GET['s'], 'channel', 'edit') . '&id=' . $row['id'] . '" >编辑</a>&nbsp;<a href="' . M($_GET['s'], 'channel', 'del') . '&id=' . $row['id'] . '" onclick="return confirm(\'确定要删除吗？\')" >删除</a></td></tr>' . channel_list_all($row['id'], $level);
  }
  return $tmp;
}

function channel_model_select_list($t0 = '')
{
  $tmp = '';
  // $res = $GLOBALS['db']->getAll("SELECT * FROM cmodel");
  $res = file_get('json', 'channel_model');
  if (!$res) return '';

  foreach ($res as $row) {
    $state = $row['value'] == $t0 ? 'selected="selected"' : '';
    $tmp .= '<option value="' . $row['value'] . '" ' . $state . '>' . $row['name'] . '</option>';
  }
  return $tmp;
}

function detail_model_select_list($t0 = '')
{
  $tmp = '';
  // $res = $GLOBALS['db']->getAll("SELECT * FROM dmodel");
  $res = file_get('json', 'detail_model');
  if (!$res) return '';

  foreach ($res as $row) {
    $state = $row['value'] == $t0 ? 'selected="selected"' : '';
    $tmp .= '<option value="' . $row['value'] . '" ' . $state . '>' . $row['name'] . '</option>';
  }
  return $tmp;
}

function priv_id($priv)
{
  if ('all' == $priv) {
    return 0;
  }
  $priv = preg_replace('/[a-z]+,?/', '', $priv);
  return rtrim(str_replace('c', '', $priv), ',');
}

//后台操作日志
function admin_log($code)
{
  if (!ADMIN_LOG) return;

  $log['admin_id'] = get_admin_token('id');
  $log['admin_name'] = get_admin_token();
  $log['log_code'] = $code;
  $log['log_time'] = local_date('Y-m-d H:i:s', gmtime());
  $log['log_ip'] = get_ip();

  \Logger::log(
    'admin_log',
    '[' . $log['admin_id'] . ':' . $log['admin_name'] . '] ' . $log['log_code']
  );

  return true;

  /*
  if (is_null(ADMIN_LOG)) {
    return false;
  }

  开启了就是后台管理否则文件存储
  if (true === ADMIN_LOG) {
    return $GLOBALS['db']->autoExecute("admin_log", $log);
  }

  if (true === ADMIN_LOG) {
    */
}

function slide_parent($parent)
{
  if (is_numeric($parent)) {
    return get_channel(intval($parent), 'c_name');
  }

  switch ($parent) {
    case 'global':
      $res = '全局';
      break;

    case 'mobile':
      $res = '手机端';
      break;

    case 'mall':
      $res = '商城';
      break;

    default:
      $res = '首页';
      break;
  }

  return $res;
}
// 自动清理超期的数据
function clear_expire($tbl, $col, $limit, $where, $id = 'id')
{
  $ids = '';
  $res = $GLOBALS['db']->getAll("SELECT {$id},{$col},{$limit} FROM {$tbl} WHERE {$where}");
  foreach ($res as $val) {
    if (gmtime() > ($val[$col] + $val[$limit])) {
      $ids .= $val[$id] . ',';
    }
  }
  if (!empty($ids)) {
    $idstr = rtrim($ids, ',');
    $sql = "DELETE FROM {$tbl} WHERE {$id} IN ({$idstr})";
    return $GLOBALS['db']->query($sql);
  }
  return false;
}

// 获取中文首字母
function get_first_letter($str)
{
  $fchar = ord($str[0]);
  if ($fchar >= ord('A') && $fchar <= ord('z')) {
    return strtoupper($str[0]);
  }
  $s1 = iconv('UTF-8', 'gb2312', $str);
  $s2 = iconv('gb2312', 'UTF-8', $s1);
  $s = $s2 == $str ? $s1 : $str;
  $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;
  if ($asc >= -20319 && $asc <= -20284) {
    $albet = 'A';
  }
  if ($asc >= -20283 && $asc <= -19776) {
    $albet = 'B';
  }
  if ($asc >= -19775 && $asc <= -19219) {
    $albet = 'C';
  }
  if ($asc >= -19218 && $asc <= -18711) {
    $albet = 'D';
  }
  if ($asc >= -18710 && $asc <= -18527) {
    $albet = 'E';
  }
  if ($asc >= -18526 && $asc <= -18240) {
    $albet = 'F';
  }
  if ($asc >= -18239 && $asc <= -17923) {
    $albet = 'G';
  }
  if ($asc >= -17922 && $asc <= -17418) {
    $albet = 'I';
  }
  if ($asc >= -17417 && $asc <= -16475) {
    $albet = 'J';
  }
  if ($asc >= -16474 && $asc <= -16213) {
    $albet = 'K';
  }
  if ($asc >= -16212 && $asc <= -15641) {
    $albet = 'L';
  }
  if ($asc >= -15640 && $asc <= -15166) {
    $albet = 'M';
  }
  if ($asc >= -15165 && $asc <= -14923) {
    $albet = 'N';
  }
  if ($asc >= -14922 && $asc <= -14915) {
    $albet = 'O';
  }
  if ($asc >= -14914 && $asc <= -14631) {
    $albet = 'P';
  }
  if ($asc >= -14630 && $asc <= -14150) {
    $albet = 'Q';
  }
  if ($asc >= -14149 && $asc <= -14091) {
    $albet = 'R';
  }
  if ($asc >= -14090 && $asc <= -13319) {
    $albet = 'S';
  }
  if ($asc >= -13318 && $asc <= -12839) {
    $albet = 'T';
  }
  if ($asc >= -12838 && $asc <= -12557) {
    $albet = 'W';
  }
  if ($asc >= -12556 && $asc <= -11848) {
    $albet = 'X';
  }
  if ($asc >= -11847 && $asc <= -11056) {
    $albet = 'Y';
  }
  if ($asc >= -11055 && $asc <= -10247) {
    $albet = 'Z';
  }
  return !empty($albet) ? $albet : null;
}